package space.enemy;

import java.util.Date;

import javax.microedition.khronos.opengles.GL10;

import org.anddev.andengine.collision.BaseCollisionChecker;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.handler.IUpdateHandler;
import org.anddev.andengine.engine.handler.collision.CollisionHandler;
import org.anddev.andengine.engine.handler.collision.ICollisionCallback;
import org.anddev.andengine.engine.handler.timer.ITimerCallback;
import org.anddev.andengine.engine.handler.timer.TimerHandler;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.shape.IShape;
import org.anddev.andengine.entity.shape.Shape;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.text.ChangeableText;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.font.Font;
import org.anddev.andengine.opengl.font.FontFactory;
import org.anddev.andengine.opengl.texture.Texture;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.opengl.texture.region.TextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TiledTextureRegion;
import org.anddev.andengine.ui.activity.BaseGameActivity;

import space.enemy.ParallaxBackground.ParallaxEntity;





import android.graphics.Color;
import android.graphics.Typeface;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;


public class SpaceEnemyController extends BaseGameActivity  implements SensorEventListener {
	
	
	private ChangeableText elapsedText;
	private int punteggioTot;
	
	PlayerProfileManager playerProfileManager;

	private float x;
	private int sX=100; // Sprite coordinates
	
	public static final int CAMERA_WIDTH = 480;
	public static final int CAMERA_HEIGHT = 320;
	static final int BORDER_SIZE = 50;
	private Camera mCamera;
	private Texture mMenuTexture;
	protected TextureRegion mMenuResetTextureRegion;
	protected TextureRegion mMenuQuitTextureRegion;
	protected TextureRegion mMenuSettingsTextureRegion;
	long lDateTime = -1;
	
	
	public Texture mLevelTexture1;
	public TextureRegion mLevelTextureRegion1;
	public Texture mTexture;
	public TiledTextureRegion mSnapdragonTextureRegion;
	public Texture mTextureAlieni;
	public TiledTextureRegion mAlieniTextureRegion;
	public Texture mBulletTexture;
	public TextureRegion mBulletTextureRegion;
	public Texture mFireButtonTexture;
	public TextureRegion mFireButtonTextureRegion;
	
	private Shuttle shuttle;
	
	space.enemy.LevelController levelController;
	private SensorManager sensorManager;
	public Texture mLevelSignTextures;
	public TextureRegion mLevelCompletedRegion;
	public TextureRegion mLevelUnCompletedRegion;
	private TextureRegion mLevelTextureRegion2;

	private TextureRegion mLevelTextureRegionLocked;

	private TextureRegion mLevelTextureRegion3;

	private TextureRegion mLevelTextureRegion4;

	private TextureRegion mLevelTextureRegion5;

	private TextureRegion mLevelTextureRegion6;

	private TextureRegion mLevelTextureRegion7;

	private Texture mAutoParallaxBackgroundTexture;

	private TextureRegion mParallaxLayerFront;

	private TextureRegion mParallaxLayerCloud;

	private AutoParallaxBackground autoParallaxBackground;

	public TiledTextureRegion mAlieniTextureRegionPar;

	//private EnemyStrong enemyStrong;

	private Texture mTextureAlieniPar;

	private Texture mMenuTextureInit;

	private TextureRegion mMenuResetTextureRegionInit;

	private Texture mFontTexture;

	public Font mFont;

	public Texture mTextureAlieniRotti;

	public TiledTextureRegion mAlieniRottiTextureRegion;

	public Texture mTextureMattone;

	protected double time;

	protected float timelapsed;
	private Font mFontPunteggio;

	

	@Override
	public Engine onLoadEngine() {
		playerProfileManager = new PlayerProfileManager(this);
		levelController = new LevelController(this);

		this.mCamera  = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
		return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera));

	}

	@Override
	public void onLoadResources() {
		
		FontFactory.setAssetBasePath("font/");
		this.mFontTexture = new Texture(512, 512, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mFont = FontFactory.createFromAsset(this.mFontTexture, this, "Plok.ttf", 12, true, Color.WHITE);
		this.mFontPunteggio = new Font(this.mFontTexture, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), 10, true, Color.BLACK);

		
		
		this.mEngine.getTextureManager().loadTexture(this.mFontTexture);
		this.mEngine.getFontManager().loadFont(this.mFont);
		this.mEngine.getFontManager().loadFont(this.mFontPunteggio);
		
		this.mAutoParallaxBackgroundTexture = new Texture( 1024,2048, TextureOptions.DEFAULT);
		this.mParallaxLayerFront = TextureRegionFactory.createFromAsset(this.mAutoParallaxBackgroundTexture, this, "gfx/fondo1-step3.png", 0, 470);
		
		this.mParallaxLayerCloud = TextureRegionFactory.createFromAsset(this.mAutoParallaxBackgroundTexture, this, "gfx/nuvole3.png", 0, 0);
		
		this.mMenuTextureInit = new Texture(512, 512, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mMenuResetTextureRegionInit = TextureRegionFactory.createFromAsset(this.mMenuTextureInit, this, "gfx/init.png", 0, 0);
		
	
		this.mMenuTexture = new Texture(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mMenuResetTextureRegion = TextureRegionFactory.createFromAsset(this.mMenuTexture, this, "gfx/menu_black_button_play.png", 0, 0);
		this.mMenuQuitTextureRegion = TextureRegionFactory.createFromAsset(this.mMenuTexture, this, "gfx/menu_black_button_quit.png", 0, 50);
		this.mMenuSettingsTextureRegion = TextureRegionFactory.createFromAsset(this.mMenuTexture, this, "gfx/menu_black_button_settings.png", 0, 100);
		
		mLevelTexture1 = new Texture(512, 512, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		mLevelTextureRegion1 = TextureRegionFactory.createFromAsset(this.mLevelTexture1, this, "gfx/level1.png", 0, 0);
		mLevelTextureRegion2 = TextureRegionFactory.createFromAsset(this.mLevelTexture1, this, "gfx/level2.png", 0, 64);
		mLevelTextureRegion3 = TextureRegionFactory.createFromAsset(this.mLevelTexture1, this, "gfx/level2.png", 0, 128);
		mLevelTextureRegion4 = TextureRegionFactory.createFromAsset(this.mLevelTexture1, this, "gfx/level1.png", 0, 256);
		mLevelTextureRegion5 = TextureRegionFactory.createFromAsset(this.mLevelTexture1, this, "gfx/level2.png", 0, 320);
		mLevelTextureRegion6 = TextureRegionFactory.createFromAsset(this.mLevelTexture1, this, "gfx/level2.png", 0, 384);
		mLevelTextureRegion7 = TextureRegionFactory.createFromAsset(this.mLevelTexture1, this, "gfx/level2.png", 0, 448);

		mLevelTextureRegionLocked = TextureRegionFactory.createFromAsset(this.mLevelTexture1, this, "gfx/level_locked_1.png", 0, 192);
		
		this.mTexture = new Texture(128, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA);

		this.mSnapdragonTextureRegion = TextureRegionFactory.createTiledFromAsset(this.mTexture, this, "gfx/navicella.png", 0, 0, 2, 1);

		//this.mTextureAlieni = new Texture(256, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		
		this.mTextureAlieni = new Texture(128, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA);

		this.mAlieniTextureRegion = TextureRegionFactory.createTiledFromAsset(this.mTextureAlieni, this, "gfx/alieniNew.png", 0, 0, 2, 1);

	
	
		 this.mBulletTexture = new Texture(8, 16, TextureOptions.BILINEAR);
         this.mBulletTextureRegion = TextureRegionFactory.createFromAsset(this.mBulletTexture, this, "gfx/Bullet.png", 0, 0);
         
        
         this.mFireButtonTexture = new Texture(64, 64, TextureOptions.BILINEAR);
         this.mFireButtonTextureRegion = TextureRegionFactory.createFromAsset(this.mFireButtonTexture, this, "gfx/fire_aus1.png", 0, 0);

         mLevelSignTextures = new Texture(128,128, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
 		mLevelCompletedRegion = TextureRegionFactory.createFromAsset(this.mLevelSignTextures, this, "gfx/ok_button.png", 0, 0);
 		mLevelUnCompletedRegion = TextureRegionFactory.createFromAsset(this.mLevelSignTextures, this, "gfx/fail_button.png", 0, 64);
		
		//texture per gestire gli alienistrong
		this.mTextureAlieniPar = new Texture(128, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mAlieniTextureRegionPar = TextureRegionFactory.createTiledFromAsset(this.mTextureAlieniPar, this, "gfx/alieniNew.png", 0, 0, 2, 1);
	
		this.mTextureAlieniRotti = new Texture(128, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mAlieniRottiTextureRegion = TextureRegionFactory.createTiledFromAsset(this.mTextureAlieniRotti, this, "gfx/alieni_rotti.png", 0, 0, 2, 1);
		
		this.mTextureMattone = new Texture(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		/*this.mMattoneTextureRegion = TextureRegionFactory.createFromAsset(this.mTextureMattone, this, "gfx/mattone1.png", 0, 0);
		this.mMattoneTextureRegion2 = TextureRegionFactory.createFromAsset(this.mTextureMattone, this, "gfx/mattone1.png", 16, 32);
		this.mMattoneTextureRegion3 = TextureRegionFactory.createFromAsset(this.mTextureMattone, this, "gfx/mattone1.png", 32, 16);
		this.mMattoneTextureRegion4 = TextureRegionFactory.createFromAsset(this.mTextureMattone, this, "gfx/mattone1.png", 32, 32);*/
		
		
		
		
		this.mEngine.registerUpdateHandler(new FPSLogger());
		this.mEngine.getTextureManager().loadTextures(mMenuTextureInit,mTextureAlieniPar,mAutoParallaxBackgroundTexture,mMenuTexture,mLevelTexture1,mTexture,mTextureAlieni,mFireButtonTexture,mBulletTexture,mLevelSignTextures,mTextureAlieniRotti,mTextureMattone);
	
	}

	@Override
	public Scene onLoadScene() {
		sensorManager = (SensorManager) this.getSystemService(this.SENSOR_SERVICE);
        sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), sensorManager.SENSOR_DELAY_GAME);
		this.mEngine.registerUpdateHandler(new FPSLogger());
	
		return createMenuScene();
	}

	@Override
	public void onLoadComplete() {
		//score();		
	}
	
public Scene createMenuScene() {
		
		final Scene scene = new Scene(2);
		//scene.setBackground(this.mMenuTextureInit);
		scene.setBackgroundEnabled(false);
		scene.attachChild(new Sprite(0, 0, this.mMenuResetTextureRegionInit));
		Sprite buttonLevel = new Sprite(100, 50, 250, 70, this.mMenuResetTextureRegion)
		{
			@Override
			public boolean onAreaTouched(TouchEvent pSceneTouchEvent,float pTouchAreaLocalX, float pTouchAreaLocalY)
			{
				if(checkTouchTime()){
					mEngine.setScene(addMenuLevelItems());
					//this..mEngine.setScene(GameLogicController.getInstance().createLevelSubmenu(currentPage));
				}
				return true;
			}

			
		};
		buttonLevel.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
		scene.registerTouchArea(buttonLevel);
		scene.getLastChild().attachChild(buttonLevel);
		
		
		buttonLevel = new Sprite(100, 130, 250, 70, this.mMenuSettingsTextureRegion)
		{
			@Override
			public boolean onAreaTouched(TouchEvent pSceneTouchEvent,float pTouchAreaLocalX, float pTouchAreaLocalY)
			{
				return true;
			}
		};
		buttonLevel.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
		scene.registerTouchArea(buttonLevel);
		scene.getLastChild().attachChild(buttonLevel);
		
		buttonLevel = new Sprite(100, 210, 250, 70, this.mMenuQuitTextureRegion)
		{
			@Override
			public boolean onAreaTouched(TouchEvent pSceneTouchEvent,float pTouchAreaLocalX, float pTouchAreaLocalY)
			{
				if(checkTouchTime())
				{
					
					finish();
				}
				return true;
			}
		};
		buttonLevel.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
		scene.registerTouchArea(buttonLevel);
		scene.getLastChild().attachChild(buttonLevel);
		
		return scene;
	}




protected Scene addMenuLevelItems(){
	Scene tempScene = new Scene(2);
	int height = 80;
	int weight = 80;
	int x =0;
	int y = 10;
	//int offset=5;
	int offsetStart = 10;
	int offset = weight+5;
	Sprite buttonLevel;
	if(playerProfileManager.isLevelUnlocked(1))
	{
		buttonLevel= new Sprite(offsetStart, y, height, weight, mLevelTextureRegion1)
			{
				@Override
				public boolean onAreaTouched(TouchEvent pSceneTouchEvent,float pTouchAreaLocalX, float pTouchAreaLocalY)
				{
					if(checkTouchTime())
						mEngine.setScene(newGameLevelScene(1));
					return true;
				}
			};
		tempScene.registerTouchArea(buttonLevel);
		tempScene.getLastChild().attachChild(buttonLevel);
	}
	else{
		buttonLevel = new Sprite(x, y, height, weight, mLevelTextureRegionLocked);
		tempScene.getLastChild().attachChild(buttonLevel);
	}
	
	x += offsetStart+offset;//aggiungo offset
	if(playerProfileManager.isLevelUnlocked(2))
	{
		buttonLevel = new Sprite(x, y, height, weight, mLevelTextureRegion2)
		{
			@Override
			public boolean onAreaTouched(TouchEvent pSceneTouchEvent,float pTouchAreaLocalX, float pTouchAreaLocalY)
			{
				if(checkTouchTime())
					mEngine.setScene(newGameLevelScene(2));
				return true;
			}
		};
		tempScene.registerTouchArea(buttonLevel);
		tempScene.getLastChild().attachChild(buttonLevel);
	}
	else{
		buttonLevel = new Sprite(x, y, height, weight, mLevelTextureRegionLocked);
		tempScene.getLastChild().attachChild(buttonLevel);
	}
	
	x +=  offset;//aggiungo offset
	if(playerProfileManager.isLevelUnlocked(3))
	{
		buttonLevel = new Sprite(x, y, height, weight, mLevelTextureRegion3)
		{
			@Override
			public boolean onAreaTouched(TouchEvent pSceneTouchEvent,float pTouchAreaLocalX, float pTouchAreaLocalY)
			{
				if(checkTouchTime())
					mEngine.setScene(newGameLevelScene(3));
				return true;
			}
		};
		tempScene.registerTouchArea(buttonLevel);
		tempScene.getLastChild().attachChild(buttonLevel);
	}
	else{
		buttonLevel = new Sprite(x, y, height, weight, mLevelTextureRegionLocked);
		tempScene.getLastChild().attachChild(buttonLevel);
	}
		
		x += offset;//aggiungo offset
		if(playerProfileManager.isLevelUnlocked(4))
		{
			buttonLevel = new Sprite(x, y, height, weight, mLevelTextureRegion4)
			{
				@Override
				public boolean onAreaTouched(TouchEvent pSceneTouchEvent,float pTouchAreaLocalX, float pTouchAreaLocalY)
				{
					if(checkTouchTime())
						mEngine.setScene(newGameLevelScene(4));
					return true;
				}
			};
			tempScene.registerTouchArea(buttonLevel);
			tempScene.getLastChild().attachChild(buttonLevel);
		}
		else{
			buttonLevel = new Sprite(x, y, height, weight, mLevelTextureRegionLocked);
			tempScene.getLastChild().attachChild(buttonLevel);
		}
			
			x +=  offset;//aggiungo offset
			if(playerProfileManager.isLevelUnlocked(5))
			{
				buttonLevel = new Sprite(x, y, height, weight, mLevelTextureRegion5)
				{
					@Override
					public boolean onAreaTouched(TouchEvent pSceneTouchEvent,float pTouchAreaLocalX, float pTouchAreaLocalY)
					{
						if(checkTouchTime())
							mEngine.setScene(newGameLevelScene(5));
						return true;
					}
				};
				tempScene.registerTouchArea(buttonLevel);
				tempScene.getLastChild().attachChild(buttonLevel);
			}
			else{
				buttonLevel = new Sprite(x, y, height, weight, mLevelTextureRegionLocked);
				tempScene.getLastChild().attachChild(buttonLevel);
			}
				//nuova riga
				x = 0;//aggiungo offset
				y+=90;
				if(playerProfileManager.isLevelUnlocked(6))
				{
					buttonLevel = new Sprite(offsetStart, y, height, weight, mLevelTextureRegion6)
					{
						@Override
						public boolean onAreaTouched(TouchEvent pSceneTouchEvent,float pTouchAreaLocalX, float pTouchAreaLocalY)
						{
							if(checkTouchTime())
								mEngine.setScene(newGameLevelScene(6));
							return true;
						}
					};
					tempScene.registerTouchArea(buttonLevel);
					tempScene.getLastChild().attachChild(buttonLevel);
				}
				else{
					
					buttonLevel = new Sprite(offsetStart, y, height, weight, mLevelTextureRegionLocked);
					tempScene.getLastChild().attachChild(buttonLevel);
				}
				x+=offsetStart+offset;
				if(playerProfileManager.isLevelUnlocked(7))
				{
				
					buttonLevel = new Sprite(x, y, height, weight, mLevelTextureRegion7)
					{
						@Override
						public boolean onAreaTouched(TouchEvent pSceneTouchEvent,float pTouchAreaLocalX, float pTouchAreaLocalY)
						{
							if(checkTouchTime())
								mEngine.setScene(newGameLevelScene(7));
							return true;
						}
					};
					tempScene.registerTouchArea(buttonLevel);
					tempScene.getLastChild().attachChild(buttonLevel);
				}
				else{
					buttonLevel = new Sprite(x, y, height, weight, mLevelTextureRegionLocked);
					tempScene.getLastChild().attachChild(buttonLevel);
				}
				x+=offset;
				if(playerProfileManager.isLevelUnlocked(8))
				{
					
					buttonLevel = new Sprite(x, y, height, weight, mLevelTextureRegion7)
					{
						@Override
						public boolean onAreaTouched(TouchEvent pSceneTouchEvent,float pTouchAreaLocalX, float pTouchAreaLocalY)
						{
							if(checkTouchTime())
								mEngine.setScene(newGameLevelScene(8));
							return true;
						}
					};
					tempScene.registerTouchArea(buttonLevel);
					tempScene.getLastChild().attachChild(buttonLevel);
				}
				else{
					buttonLevel = new Sprite(x, y, height, weight, mLevelTextureRegionLocked);
					tempScene.getLastChild().attachChild(buttonLevel);
				}
	return tempScene;
		
}
protected Scene newGameLevelScene(int i) {

	final Scene scene = new Scene(2);
	final int centreX = (CAMERA_WIDTH - this.mSnapdragonTextureRegion.getWidth()) / 2;
	final int centreY = (CAMERA_HEIGHT - this.mSnapdragonTextureRegion.getHeight());
	
	elapsedText = new ChangeableText(10, 10, this.mFontPunteggio, "Seconds elapsed:", "Seconds elapsed: XXXXX".length());
	scene.getLastChild().attachChild(elapsedText);
	shuttle = new Shuttle(centreX, centreY, this.mSnapdragonTextureRegion,100,scene);
	//enemyStrong = new EnemyStrong(20,20, mAlieniTextureRegionPar,100,scene);
	
   
	levelController.setScene(scene);
	levelController.setmEngine(mEngine);
	levelController.setShuttle(shuttle);
	levelController.loadLevel(i);
	
	 autoParallaxBackground = new AutoParallaxBackground(0, 0, 0, 5);
	ParallaxEntity parallaxLayerFront = new AutoParallaxBackground.ParallaxEntity(0.0f,5.0f,false,true, new Sprite(0, 0, this.mParallaxLayerFront));
	ParallaxEntity parallaxLayerCloud = new AutoParallaxBackground.ParallaxEntity(0.0f,5.0f,false,true, new Sprite(0,  CAMERA_HEIGHT - this.mParallaxLayerCloud.getHeight(), this.mParallaxLayerCloud));
	
	autoParallaxBackground.addParallaxEntity(parallaxLayerFront);
	autoParallaxBackground.addParallaxEntity(parallaxLayerCloud);
	
	scene.setBackground(autoParallaxBackground);

	scene.registerUpdateHandler(new IUpdateHandler() {
        public void onUpdate(float pSecondsElapsed) {
        	
        	if(levelController.getEnemyManager().getSpaceEnemyList().size()!=0){
              	
  
        		levelController.getEnemyManager().update(true);
        		levelController.getBulletManager().update(shuttle.getX()+ shuttle.getWidth()/2,shuttle.getY());
        		
        		/*if (levelController.getEnemyManager().getSpaceEnemyList().size() == 3){
        			enemyStrong = new EnemyStrong(20,20, mAlieniTextureRegionPar,100,scene);
        			
        		}
            	if (enemyStrong != null){
	        		boolean moveDown=true;
	            	if(enemyStrong.getY()>CAMERA_HEIGHT - (int)shuttle.getHeight()){
	            		moveDown = false;
	            	}
	        		enemyStrong.update(moveDown);
	            }*/

            	updateSpritePosition();
        	}
        	else{
        		punteggioTot += levelController.getEnemyManager().getPunteggio();
				System.out.println("Vittoria!BUUUUUUUUUUUU"+punteggioTot+time);

				levelController.getScene().unregisterUpdateHandler(this);
        		shuttle.stopAnimation();
        		levelController.showSignCompleted();
        		autoParallaxBackground.stop=true;
        	}
        	if(!shuttle.isAlive()){
        		punteggioTot += levelController.getEnemyManager().getPunteggio();
    			
        		//System.out.println("Hai Perso!Rosiconeeee "+punteggioTot);
        		shuttle.stopAnimation();
        		levelController.getEnemyManager().haltEnemies();
        		levelController.getScene().unregisterUpdateHandler(this);       		
        		levelController.showSignUncompleted();
        		autoParallaxBackground.stop=true;

        	}
        }
		public void reset() {
        }
    });
	//loop che abilita il fire bullet ogni mezzo secondo
	scene.registerUpdateHandler( new TimerHandler(0.5f, new ITimerCallback() {
		
		@Override
		public void onTimePassed(TimerHandler pTimerHandler) {
			if ( shuttle.isAlive() == true ) {
				pTimerHandler.reset();
				levelController.getBulletManager().enableShooting();
			}				
		}
		
	}));
	/*this.mEngine.registerUpdateHandler(new TimerHandler(1.0f, true, new ITimerCallback() {
        @Override
        public void onTimePassed(final TimerHandler pTimerHandler) {
                if (mEngine.isRunning()) {
                        time += 1.0;
                        elapsedText.setText("Seconds elapsed: " + time);
                        
                }
               
        }
       
	}));*/
	//loop che abilita il fire bullet ogni mezzo secondo
	scene.registerUpdateHandler( new TimerHandler(15.5f, new ITimerCallback() {
		
		@Override
		public void onTimePassed(TimerHandler pTimerHandler) {
			pTimerHandler.reset();
			if (levelController.getEnemyManager().getSpaceEnemyList().size()%2 ==0){ //abilito l'enemystrong ogni 15 sec circa e i nemici sono multipli di 4
				//pTimerHandler.reset();
				levelController.getEnemyManager().enableEnemyStrong();
			}				
		}
		
	}));
	scene.registerUpdateHandler(new TimerHandler(1 / 20.0f, true, new ITimerCallback() {
		@Override
		public void onTimePassed(final TimerHandler pTimerHandler) {
			timelapsed += pTimerHandler.getTimerSeconds();
			elapsedText.setText("Seconds elapsed: " + timelapsed);
			
		}
	}));
	
	scene.registerUpdateHandler(new CollisionHandler( new CollisionManager(), shuttle, levelController.getEnemyManager().getSpaceEnemyList() ));
	scene.registerUpdateHandler(new CollisionHandler( new CollisionManager(), shuttle, levelController.getEnemyManager().getEnemyStrong()));
	return scene;
	
}

	public float  getTimeElapsed() {
		// TODO Auto-generated method stub
		return timelapsed;
	}


	public int getPunteggioTot() {
		return (int) (punteggioTot);
	}
	
	public void setPunteggioTot(int punteggioTot) {
		this.punteggioTot = punteggioTot;
	}
	public Shuttle getShuttle() {
		return shuttle;
	}
	
	public void setShuttle(Shuttle shuttle) {
		this.shuttle = shuttle;
	}
	public boolean checkTouchTime(){
		
		if(lDateTime == -1)
		{
			lDateTime = new Date().getTime();
			return true;
		}
		
		long lDateCurrentTime = new Date().getTime();
		if(lDateCurrentTime - lDateTime > 500)
		{
			lDateTime = lDateCurrentTime;
			return true;
		}
		return false;
	}

@Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
	// TODO Auto-generated method stub
	
}

@Override
public void onSensorChanged(SensorEvent event) {
	switch (event.sensor.getType()) {
    case Sensor.TYPE_ACCELEROMETER:
        this.x = (int)event.values[1];
		//System.out.println("ACCELLERAZIONE2:"+(int)event.values[1]);

        //accellerometerSpeedY = (int)event.values[0];
        break;
}	
}
protected void updateSpritePosition() {
	if ((x != 0)) {
        // Set the Boundary limits
        int tL = 0;
        int lL = 0;
        int rL = CAMERA_WIDTH - (int)this.shuttle.getWidth();
        int bL = CAMERA_HEIGHT - (int)this.shuttle.getHeight();

        // Calculate New X,Y Coordinates within Limits
        if (sX >= lL) sX += x; else sX = lL;
        if (sX <= rL) sX += x; else sX = rL;
       

        // Double Check That New X,Y Coordinates are within Limits
        if (sX < lL)      sX = lL;
        else if (sX > rL) sX = rL;
        

        this.shuttle.setPosition(sX, bL);
    }
	}
	public void score(){
	    this.mEngine.registerUpdateHandler(new TimerHandler(1.0f, true, new ITimerCallback() {
	            @Override
	            public void onTimePassed(final TimerHandler pTimerHandler) {
	                    if (mEngine.isRunning()) {
	                            time += 1.0;
	                            elapsedText.setText("Seconds elapsed: " + time);
	                            
	                    }
	                   
	            }
	           
	    }));
	}
	static class CollisionManager implements ICollisionCallback {
	
	@Override
	public boolean onCollision(IShape pCheckShape, IShape pTargetShape) {
		
		Shuttle ship = (Shuttle) pCheckShape;
		
		if  ( ship.isAlive() && checkCollisions(pCheckShape,pTargetShape)) {
			
			ship.setLife(0);
			SpaceEnemy enemy = (SpaceEnemy) pTargetShape;
			//enemy.decreaseLife(SpaceEnemy.HEALTH);
			return true;//blocca il collision handler
		}
		
		return false; 
	

		
	}
			
	public static boolean checkCollisions(IShape pCheckShape, IShape pTargetShape) {
		return BaseCollisionChecker.checkAxisAlignedRectangleCollision( pCheckShape.getX(), pCheckShape.getY(), 
				pCheckShape.getX() + pCheckShape.getWidth(), pCheckShape.getY() + pCheckShape.getHeight(),
				pTargetShape.getX(), pTargetShape.getY(), 
				pTargetShape.getX() + pTargetShape.getWidth(), pTargetShape.getY() + pTargetShape.getHeight());
				
	}
	
}

}
